package nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class NioServer {

    public static void main(String[] args) {
        new NioServer().apiServe();
    }

    /**
     * 模拟Selector的原理
     * 一个线程管理通过保存、轮询管理多个IO
     * 实现IO多路复用
     */
    public void serve() {
        try {
            // 创建通道
            ServerSocketChannel serverSocket = ServerSocketChannel.open();
            // 绑定ip、端口
            serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 3333));
            // 设置非阻塞
            serverSocket.configureBlocking(false);

            List<SocketChannel> socketChannelList = new LinkedList<>();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int read;
            while (true) {
                SocketChannel socketChannel = serverSocket.accept();
                if (socketChannel != null) {
                    socketChannel.configureBlocking(false);
                    socketChannelList.add(socketChannel);
                }
                for (SocketChannel s : socketChannelList) {
                    read = s.read(buffer);
                    if (read > 0) {
                        buffer.flip();
                        String mes = StandardCharsets.UTF_8
                                .newDecoder()
                                .decode(buffer.asReadOnlyBuffer())
                                .toString();
                        System.out.println("Server receive:" + mes);
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * windows下的selector使用的就是轮询的机制 select
     * linux下提供epoll，通过回调来获取哪些连接有效 => 所以linux更加高效
     */
    public void apiServe() {
        try (Selector selector = Selector.open();
             ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
            serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 3333));
            serverSocket.configureBlocking(false);

            // 将server通道注册到选择器 SelectionKey.OP_ACCEPT 事件
            // 当accept事件到达时，selector.select()才会返回，否则阻塞
            serverSocket.register(selector, SelectionKey.OP_ACCEPT, SelectionKey.OP_WRITE);
            while (true) {
                selector.select(); // waiting for active channels
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove(); // delete handled key

                    if (key.isAcceptable()) { /* server is about to accept channel */
                        SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept(); // accept channel
                        clientChannel.configureBlocking(false); // set none blocking
                        clientChannel.register(selector, SelectionKey.OP_READ); // register to selector
                        clientChannel.write(StandardCharsets.UTF_8.encode("from server: connected\n"));
                    } else if (key.isReadable()) { /* handle mes from client */
                        manage(key);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param key
     */
    private void manage(SelectionKey key) {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            if (channel.read(buffer) > 0) {
                String mes = new String(buffer.array()).trim();
                System.out.println("server receive:" + mes);
                channel.write(ByteBuffer.wrap("hello".getBytes()));
            }
        } catch (IOException e) {
            try { /* handle disconnection */
                System.out.println(channel.getRemoteAddress() + "--exit");
                key.cancel();
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
